package com.drinkian.business.room.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.drinkian.authentication.entity.po.User;
import com.drinkian.authentication.mapper.UserMapper;
import com.drinkian.business.room.entity.po.Room;
import com.drinkian.business.room.entity.po.RoomPicture;
import com.drinkian.business.room.entity.vo.VRoomAdd;
import com.drinkian.business.room.entity.vo.VRoomGet;
import com.drinkian.business.room.mapper.RoomMapper;
import com.drinkian.business.room.mapper.RoomPictureMapper;
import com.drinkian.business.room.service.IRoomService;
import com.drinkian.entity.RequestResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

@Service
public class RoomServiceImpl implements IRoomService {

    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private RoomPictureMapper roomPictureMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public RequestResult addRoom(VRoomAdd vRoomAdd) {
        vRoomAdd.setPrice(String.valueOf((int) (Double.valueOf(vRoomAdd.getPrice()) * 100)));
        Room room = new Room();
        BeanUtils.copyProperties(vRoomAdd, room);
        int result = roomMapper.addRoomBasic(room);
        if (result == 1) {
            for (String image : vRoomAdd.getImageArr()) {
                roomMapper.addRoomImage(room.getId(), image);
            }
            return new RequestResult(HttpStatus.OK.value(), "添加成功！请等待审核通过！");
        } else {
            return new RequestResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), "添加房屋信息出现了错误");
        }
    }

    @Override
    public RequestResult getRoomList(int current, int size) {
        IPage<VRoomGet> vRoomGetIPage = new Page<>(current, size);
        List<VRoomGet> roomGets = roomMapper.getRoomList(vRoomGetIPage).getRecords();
        for (VRoomGet vRoomGet : roomGets) {
            List<String> roomImageList = roomMapper.getRoomImageList(vRoomGet.getRoomId());
            vRoomGet.setRoomImage(roomImageList);
        }
        return new RequestResult(HttpStatus.OK.value(), roomGets);
    }

    @Override
    public RequestResult searchRoomListByTitle(String title) {
        List<VRoomGet> vRoomGets = roomMapper.searchRoom(title);
        for (VRoomGet vRoomGet : vRoomGets) {
            List<String> RoomImageList = roomMapper.getRoomImageList(vRoomGet.getRoomId());
            vRoomGet.setRoomImage(RoomImageList);
        }
        return new RequestResult(HttpStatus.OK.value(), vRoomGets);
    }

    @Override
    public RequestResult getRoomListByUploaderId(int current, int size, Integer uploaderId) {
        IPage<Room> roomPage = new Page<>(current, size);
        QueryWrapper<Room> roomQueryWrapper = new QueryWrapper<>();
        roomQueryWrapper.eq("uploader_id", uploaderId).orderByDesc("modify_time");
        IPage<Room> roomIPage = roomMapper.selectPage(roomPage, roomQueryWrapper);
        for (Room room : roomIPage.getRecords()) {
            QueryWrapper<RoomPicture> roomPictureQueryWrapper = new QueryWrapper<>();
            roomPictureQueryWrapper.eq("room_id", room.getId());
            List<RoomPicture> imageList = roomPictureMapper.selectList(roomPictureQueryWrapper);
            room.setImageList(imageList);
        }
        return new RequestResult(HttpStatus.OK.value(), roomIPage);
    }

    @Override
    public RequestResult deleteRoomById(Integer id) {
        UpdateWrapper<Room> roomUpdateWrapper = new UpdateWrapper<>();
        roomUpdateWrapper.eq("id", id).set("deleted", 1);
        int roomRows = roomMapper.update(null, roomUpdateWrapper);
        if (roomRows == 1) {
            UpdateWrapper<RoomPicture> roomPictureUpdateWrapper = new UpdateWrapper<>();
            roomPictureUpdateWrapper.eq("room_id", id).set("deleted", 1);
            int roomPictureRows = roomPictureMapper.update(null, roomPictureUpdateWrapper);
            if (roomPictureRows > 0) {
                return new RequestResult(HttpStatus.OK.value(), "删除成功！");
            } else {
                return new RequestResult(HttpStatus.OK.value(), "房屋删除成功！相关图片未删除成功！");
            }
        } else {
            return new RequestResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), "删除失败！");
        }
    }

    @Override
    public RequestResult updateRoom(Room room) {
        room.setModifyTime(null);
        room.setPrice(String.valueOf((int) (Double.valueOf(room.getPrice()) * 100)));
        int result = roomMapper.updateById(room);
        if (result == 1) {
            return new RequestResult(HttpStatus.OK.value(), "更新成功！");
        } else {
            return new RequestResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), "更新失败！");
        }
    }

    @Override
    public RequestResult getUncheckRoomList(Integer current, Integer size) {
        IPage<Room> iPage = new Page<>(current, size);
        QueryWrapper<Room> roomQueryWrapper = new QueryWrapper<>();
        roomQueryWrapper.eq("status", 0);
        IPage<Room> roomIPage = roomMapper.selectPage(iPage, roomQueryWrapper);
        Iterator<Room> iterator = roomIPage.getRecords().iterator();
        while (iterator.hasNext()) {
            Room next = iterator.next();
            // 添加上传人信息
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
            userQueryWrapper.eq("status", 2);
            userQueryWrapper.eq("id", next.getUploaderId());
            User uploader = userMapper.selectOne(userQueryWrapper);

            // 用户不存在或者违规
            if (Objects.isNull(uploader)) {
                iterator.remove();
            } else {
                next.setUploader(uploader);
            }

            // 添加商品图片信息
            QueryWrapper<RoomPicture> roomPictureQueryWrapper = new QueryWrapper<>();
            roomPictureQueryWrapper.eq("status", 1);
            roomPictureQueryWrapper.eq("deleted", 0);
            roomPictureQueryWrapper.eq("room_id", next.getId());
            List<RoomPicture> pictures = roomPictureMapper.selectList(roomPictureQueryWrapper);
            next.setImageList(pictures);
        }
        return new RequestResult(HttpStatus.OK.value(), roomIPage);
    }

    @Override
    public RequestResult examUncheckRoom(Integer roomId, Integer code) {
        QueryWrapper<Room> roomQueryWrapper = new QueryWrapper<>();
        roomQueryWrapper.eq("id", roomId);
        roomQueryWrapper.eq("status", 0);
        Room room = roomMapper.selectOne(roomQueryWrapper);
        // 审核失败
        if (code == 0) {
            room.setStatus(2);
            int update = roomMapper.updateById(room);
            if (update == 1) {
                // 获得商品发布人信息
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("id", room.getUploaderId());
                User uploader = userMapper.selectOne(userQueryWrapper);

                // 发送通知邮件
                SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
                simpleMailMessage.setSubject("HBUShop发布审核结果");
                simpleMailMessage.setText("您在 " + room.getCreateTime().format(dateTimeFormatter) + " 发布的  " + room.getTitle() + " 未通过审核，请修改后重新提交！");
                simpleMailMessage.setFrom("2294422096@qq.com");
                simpleMailMessage.setTo(uploader.getEmail());
                javaMailSender.send(simpleMailMessage);
                return new RequestResult(HttpStatus.OK.value(), "驳回成功！");
            } else {
                return new RequestResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务器错误！");
            }
        } else if (code == 1) {         // 审核通过
            room.setStatus(1);
            int update = roomMapper.updateById(room);
            if (update == 1) {
                // 获得商品发布人信息
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("id", room.getUploaderId());
                User uploader = userMapper.selectOne(userQueryWrapper);

                // 发送通知邮件
                SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
                simpleMailMessage.setSubject("HBUShop发布审核结果");
                simpleMailMessage.setText("您在 " + room.getCreateTime().format(dateTimeFormatter) + " 发布的  " + room.getTitle() + " 已经通过了审核！");
                simpleMailMessage.setFrom("2294422096@qq.com");
                simpleMailMessage.setTo(uploader.getEmail());
                javaMailSender.send(simpleMailMessage);
                return new RequestResult(HttpStatus.OK.value(), "审核通过！");
            } else {
                return new RequestResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务器错误！");
            }
        } else {
            return new RequestResult(HttpStatus.BAD_REQUEST.value(), "提交的参数有误！");
        }
    }

}
